package com.blog.wl2023.service.user;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.mail.MailUtil;
import com.blog.wl2023.config.SaToken.StpAdminUtil;
import com.blog.wl2023.entity.Role;
import com.blog.wl2023.entity.TokenInfo;
import com.blog.wl2023.entity.User;
import com.blog.wl2023.entity.response.Result;
import com.blog.wl2023.repository.RoleRepository;
import com.blog.wl2023.repository.UserRepository;
import com.blog.wl2023.utils.CommUtil;
import com.blog.wl2023.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

import static cn.hutool.extra.mail.MailUtil.send;

/**
 * @author wule
 * @data 2023年08月15日23时
 * @description
 */
@Service
public class UserService {
	@Autowired
	private UserRepository userRepository;

	@Autowired
	private RoleRepository roleRepository;

	public List<User> findAllUser() {
		return userRepository.findAll();
	}

	/**
	 * 获取注册时接收的验证码
	 *
	 * @param user email,password,username
	 */
	public Result getRegisterCode(User user){
		//接受到用户信息,用户名,密码,邮箱
		//判断是否有相同邮箱,直接返回"该账号已注册,请尝试找回密码",
		User userByEmail = userRepository.findUserByEmail(user.getEmail());
		if (!BeanUtil.isEmpty(userByEmail)) {
			//存在
			return Result.fail(201, "该账号已注册,你可以试试找回密码");
		} else {
			//生成并且返回验证码,并且直接插入到前端注册表单
			String code = CommUtil.generateRandomCode(6);
			return Result.ok(code);
		}
	}

	/**
	 * 找回密码时接受的验证码
	 *
	 * @param user email
	 */
	public Result getRecoverPasswordCode(User user) {
		//判断该邮箱是否注册
		User userByEmail = userRepository.findUserByEmail(user.getEmail());
		if (!BeanUtil.isEmpty(userByEmail)) {
			//存在
			//生成并且返回验证码,数据库插入code
			String code = CommUtil.generateRandomCode(6);
			//发送验证码到邮箱
			send(user.getEmail(), "找回密码通知",
					"<h1>验证码:" + code + "</h1></br>感谢您使用PRIEST网站。如非您本人操作，请忽略此邮件。",
					true);
			//将code赋值给用户
			userByEmail.setCode(code);
			userRepository.save(userByEmail);
			return Result.ok();
		}
		return Result.fail(201, "该账号未注册");
	}

	/**
	 * 更新密码
	 *
	 * @param user email code newPassword
	 */
	public Result recoverPassword(User user) {
		//通过邮箱找到用户
		User userByEmail = userRepository.findUserByEmail(user.getEmail());
		//比对验证码
		if (Objects.equals(userByEmail.getCode(), user.getCode())) {
			//成功
			//将新密码加密后插入数据库,然后清空验证码
			//密码采用aes对称加密
			String password = MD5Util.AESEnCode(user.getPassword());
			userByEmail.setPassword(password);
			userByEmail.setCode("");
			userRepository.save(userByEmail);
			//返回成功
			return Result.ok();
		} else {
			//失败
			//返回'验证码错误'
			return Result.fail(201, "验证码错误");
		}
	}

	/**
	 * 用户注册
	 *
	 * @param user 接收到的参数
	 */
	public Result userRegister(User user) {
		//生成的UUID是带-的字符串
		String uuid = IdUtil.randomUUID();
		//往邮箱发送注册成功信息,PRIEST
		MailUtil.send(user.getEmail(),
				"注册成功通知",
				"尊敬的用户:<br>"
						+ "恭喜您成功注册成为<PRIEST>网站的会员！我们非常欢迎您的加入，希望您能在PRIEST网站的各项服务中获得愉快的体验。<br>"
						+ "请记住您的登录凭据：<br>"
						+ "邮箱："+user.getEmail()+"<br>"
						+ "密码："+user.getPassword()+"<br>"
						+ "如有任何问题或需要帮助，请随时联系我们的客服团队。祝您在<PRIEST>网站度过美好的时光！<br>"
						+ "---- PRIEST团队",
				false);
		//密码采用aes对称加密
		String password = MD5Util.AESEnCode(user.getPassword());
		user.setStatus("1");
		user.setUuid(uuid);
		user.setPassword(password);
		user.setImageUrl("default-user-image-url.jpg");
		userRepository.save(user);
		//返回注册成功
		return Result.ok();
	}

	/**
	 * 用户登录
	 *
	 * @param user 接收到的参数
	 */
	public Result userLogin(User user) {
		User userByEmail = userRepository.findUserByEmail(user.getEmail());
		//获取用户信息,通过邮箱和密码进行比对
		if (!BeanUtil.isEmpty(userByEmail)) {
			String oldPassword = MD5Util.AESDeCode(userByEmail.getPassword());
			if (userByEmail.getStatus().equals("0")){
				return Result.fail(201, "该账号未注册或被限制登录! 请联系管理员");
			}
			if (oldPassword.equals(user.getPassword())) {
				//比对成功
				//将用户通过sa-token保存,并返回token
				Role roleByUserId = roleRepository.findRoleByUserId(userByEmail.getUuid());
				SaTokenInfo tokenInfo;
				if (roleByUserId==null){
					StpUtil.login(userByEmail.getUuid());
					tokenInfo = StpUtil.getTokenInfo();
				}else {
					StpAdminUtil.login(userByEmail.getUuid());
					tokenInfo = StpAdminUtil.getTokenInfo();
				}
				userByEmail.setTokenInfo(new TokenInfo(tokenInfo.tokenName, tokenInfo.tokenValue));
				return Result.ok(userByEmail);
			}else {
				return Result.fail(201, "密码错误!");
			}
		} else {
			return Result.fail(201, "该账号未注册!");
		}

	}

	public void updateUserAvatar(String uuid, String fileName) {
		userRepository.updateUserAvatar(uuid,fileName);
	}

	public Result verifyLogin() {
		//获取用户信息,判断用户是否登录,未登录则去除本地信息,
		//已登陆不做改变
		boolean login = StpUtil.isLogin()||StpAdminUtil.isLogin();
		return Result.ok(login);
	}
}
